import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_shop/net/interceptor.dart';
import 'package:flutter_shop/net/net.dart';
import 'package:flutter_shop/res/constant.dart';
import 'package:flutter_shop/routers/not_found_page.dart';
import 'package:flutter_shop/routers/routers.dart';
import 'package:flutter_shop/setting/provider/locale_provider.dart';
import 'package:flutter_shop/setting/provider/theme_provider.dart';
import 'package:flutter_shop/utils/utils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:quick_actions/quick_actions.dart';
import 'package:url_strategy/url_strategy.dart';
import 'package:window_manager/window_manager.dart';

import 'home/splash_page.dart';

Future<void> main() async {

  /// 确保初始化完成
  WidgetsFlutterBinding.ensureInitialized();

  if (Device.isDesktop) {
    await WindowManager.instance.ensureInitialized();
    windowManager.waitUntilReadyToShow().then((_) async {
      // 隐藏标题
      await windowManager.setTitleBarStyle(TitleBarStyle.hidden,windowButtonVisibility: false);
      await windowManager.setSize(const Size(400, 800));
      await windowManager.setMinimumSize(const Size(400, 800));
      // 居中显示
      await windowManager.center();
      await windowManager.show();
      await windowManager.setPreventClose(false);
      await windowManager.setSkipTaskbar(false);
    });
  }
  /// 去除URL中的“#”(hash)，仅针对Web。默认为setHashUrlStrategy
  /// 注意本地部署和远程部署时`web/index.html`中的base标签，https://github.com/flutter/flutter/issues/69760
  setPathUrlStrategy();
  /// sp初始化
  await SpUtil.getInstance();

  handleError(() => runApp(MyApp()));

  /// 隐藏状态栏。为启动页、引导页设置。完成后修改回显示状态栏。
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,overlays: [SystemUiOverlay.bottom]);
}

class MyApp extends StatelessWidget {
   MyApp({super.key, this.home, this.themeData}) {
    Dlog.init();
    initDio();
    Routes.initRoutes();
    initQuickActions();
  }


  final Widget? home;
  final ThemeData? themeData;
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  void initDio() {
    final List<Interceptor> interceptors = <Interceptor>[];

    /// 统一添加身份验证请求头
    interceptors.add(AuthInterceptor());

    /// 刷新Token
    interceptors.add(TokenInterceptor());

    /// 打印log，
    if (!Constant.inProduction) {
      interceptors.add(LoggingInterceptor());
    }

    /// 适配数据
    interceptors.add(AdapterInterceptor());

    configDio(
        baseUrl: 'https://api.github.com/',
        interceptors: interceptors
    );

  }

  void initQuickActions() {
    if (Device.isMobile) {
      const QuickActions quickActions = QuickActions();
      if (Device.isIOS) {
        // Android每次是重新启动activity，所以放在了splash_page处理。
        // 总体来说使用不方便，这种动态的方式在安卓中局限性高。这里仅做练习使用。
        quickActions.initialize((String shortcutType) async {
          if (shortcutType == 'demo') {
            navigatorKey.currentState?.push<dynamic>(MaterialPageRoute<dynamic>(
              builder: (BuildContext context) => const Center()// DemoPage(),
            ));
          }
        });
      }

      quickActions.setShortcutItems(<ShortcutItem>[
        const ShortcutItem(
            type: 'demo',
            localizedTitle: 'Demo',
            icon: 'flutter_dash_black'
        ),
      ]);
    }
  }

  @override
  Widget build(BuildContext context) {
    final Widget app =  ChangeNotifierProvider(
        create: (_) => ThemeProvider(),
      child: Consumer(
        builder: (
            BuildContext context,
            ThemeProvider value, Widget? child) {
          return _buildMaterialApp(value);
          },
      ),
    );
    /// Toast 配置
    return OKToast(
        backgroundColor: Colors.black54,
        textPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
        radius: 20.0,
        position: ToastPosition.bottom,
        child: app
    );
  }

   Widget _buildMaterialApp(ThemeProvider provider) {
     return MaterialApp(
       title: 'Flutter Deer',
       // showPerformanceOverlay: true, //显示性能标签
       // debugShowCheckedModeBanner: false, // 去除右上角debug的标签
       // checkerboardRasterCacheImages: true,
       // showSemanticsDebugger: true, // 显示语义视图
       // checkerboardOffscreenLayers: true, // 检查离屏渲染

       theme: themeData ?? provider.getTheme(),
       darkTheme: provider.getTheme(isDarkMode: true),
       themeMode: provider.getThemeMode(),
       home: home ?? const SplashPage(),
       onGenerateRoute: Routes.router.generator,
       // localizationsDelegates: DeerLocalizations.localizationsDelegates,
       // supportedLocales: DeerLocalizations.supportedLocales,
       // locale: localeProvider.locale,
       navigatorKey: navigatorKey,
       builder: (BuildContext context, Widget? child) {
         /// 仅针对安卓
         if (Device.isAndroid) {
           /// 切换深色模式会触发此方法，这里设置导航栏颜色
           ThemeUtils.setSystemNavigationBar(provider.getThemeMode());
         }

         /// 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
         return MediaQuery(
           data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
           child: child!,
         );
       },

       /// 因为使用了fluro，这里设置主要针对Web
       onUnknownRoute: (_) {
         return MaterialPageRoute<void>(
           builder: (BuildContext context) => const NotFoundPage(),
         );
       },
       restorationScopeId: 'app',
     );
   }
}
